<script setup>
import { ref, inject, computed, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from "element-plus";
import { Edit, Plus, Delete, Refresh, Check } from '@element-plus/icons-vue';

const http = inject('$http'),
	tools = inject('$tools');

let data = ref([]),
	list = ref([]),
	temp = ref({}),
	editForm = ref(),
	fetching = ref(false),
	submiting = ref(false),
	showEditForm = ref(false),
	permissionList = ref(null);

const defaultProps = { children: 'children', label: 'name' }

const fetch = async function () {
	fetching.value = true;
	const res = await http.get('/rbac/menu');
	fetching.value = false;
	if (res.code === 200) {
		data.value = res.data.rows
		if (res.data.rows) {
			list.value = res.data.rows
		}
	}
}

const modelTemplate = {
	id: undefined, permission_id: 0, parent_id: 0, url: '', order: 99,
	additional: '', icon: 'minus', show: '1', description: '', name: ''
}

function resetTemp(parent_id = 0) {
	temp.value = tools.deepCopy(modelTemplate);
	temp.value.parent_id = parent_id;
}

const handleCreate = function () {
	resetTemp()
	showEditForm.value = true
	nextTick(() => {
		editForm.value.clearValidate()
	})
}

const submitForm = function () {
	editForm.value.validate(async (valid) => {
		if (!valid) return;
		let res;
		submiting.value = true;
		if (temp.value.id) {
			res = await http.put('/rbac/menu', temp.value);
		} else {
			res = await http.post('/rbac/menu', temp.value);
		}
		let messageType = 'danger';
		if (res && res.code === 200) {
			showEditForm.value = false;
			messageType = 'success';
			fetch()
		}
		if (res && res.hasOwnProperty('message')) {
			ElMessage({ type: messageType, message: res.message })
		}
		submiting.value = false;
	})
}

const handleAdd = function (data) {
	console.log('handleAdd', data)
	resetTemp(data.id)
	showEditForm.value = true
	nextTick(() => {
		editForm.value.clearValidate()
	})
}
const handleEdit = function (data) {
	console.log('handleEdit', data)
	temp.value = tools.deepCopy(data)
	temp.value.show = temp.value.show.toString();
	showEditForm.value = true
	nextTick(() => {
		editForm.value.clearValidate()
	})
}

const handleDelete = async function (row) {
	ElMessageBox.confirm(`确定删除名为 '${row.name}' 的菜单吗？`, "提示", {
		confirmButtonText: "确定", cancelButtonText: "取消", type: "error",
	}).then(async () => {
		const response = await http.delete('/rbac/menu', { ids: row.id });
		if (response.code === 200) {
			fetch()
		}
	}).catch(() => { });
}

const changeParent = function (value) {
	temp.value.permission_id = value ? value[value.length - 1] : 0
}

const getPermissionList = async function () {
	const res = await http.get('/rbac/permission');
	if (res.code === 200) {
		permissionList.value = res.data.rows
	}
}
const rules = {
	name: [{ required: true, message: '菜单名称不能为空', trigger: 'blur' }],
	icon: [{ required: true, message: '请选择图标', trigger: 'blur' }],
	url: [{ required: true, message: '请选输入路由', trigger: 'blur' }]
}
const props = {
	value: 'id', label: 'name', children: 'children', checkStrictly: true
}

const formShowIcon = computed(() => {
	const plit = temp.value.icon.indexOf(' ');
	if (plit === -1) return ['fas', temp.value.icon];
	return temp.value.icon.split(' ');
})

getPermissionList();

fetch();

</script>
<template>
	<h1 class="page-title">菜单管理</h1>
	<el-form :inline="true" @submit.native.prevent="fetch" class="search-form">
		<el-form-item>
			<el-button type="primary" :icon="Refresh" :loading="fetching" :disabled="fetching"
				native-type="submit">刷新</el-button>
		</el-form-item>
		<el-form-item fixed="right">
			<el-button type="success" :icon="Plus" @click="handleCreate">
				添加
			</el-button>
		</el-form-item>
	</el-form>
	<div class="list-box">
		<el-table :data="data" :loading="fetching" style="width: 100%;margin-bottom: 20px;" row-key="id"
			:tree-props="defaultProps">
			<el-table-column prop="name" label="菜单标题" width="180" />
			<el-table-column prop="order" label="排序" width="100" />
			<el-table-column prop="url" label="路由" width="320" />
			<el-table-column prop="description" label="描述" />
			<el-table-column prop="created_at" label="创建日期" width="180" />
			<el-table-column label="操作" width="200">
				<template #default="scope">
					<el-button v-if="scope.row.depth < 1" type="success" size="small" :icon="Plus"
						@click="handleAdd(scope.row)" />
					<el-button type="primary" size="small" :icon="Edit" @click="handleEdit(scope.row)" />
					<el-button type="danger" size="small" :icon="Delete" @click="handleDelete(scope.row)" />
				</template>
			</el-table-column>
		</el-table>
	</div>
	<el-dialog ref="EditContainer" :title="temp.id ? '编辑' : '添加'" :width="'700px'" v-model="showEditForm"
		@close="resetTemp">
		<template #default>
			<el-form ref="editForm" :rules="rules" :model="temp" label-width="80px" style="margin:5px 20px;">
				<el-row>
					<el-col :span="12">
						<el-form-item label="菜单标题" prop="name">
							<el-input v-model="temp.name" />
						</el-form-item>
						<el-form-item label="跳转路由" prop="url">
							<el-input v-model="temp.url">
								<template slot="prepend">@</template>
							</el-input>
						</el-form-item>
						<el-form-item label="菜单icon" prop="icon">
							<div style="display:flex;align-items:center;width: 280px;">
								<el-input v-model="temp.icon" placeholder="font-awesome 图标，去除前缀 如 ‘fa-heart’ 只需要输入 ‘heart’">
									<template #prefix>
										<el-button type="primary" size="small" circle style="text-align: center;">
											<font-awesome-icon v-if="temp.icon" size="lg" color="#fff"
												:icon="formShowIcon" />
										</el-button>
									</template>
								</el-input>
							</div>
						</el-form-item>
						<el-form-item label="是否显示" :rules="{ required: true }">
							<el-switch v-model="temp.show" active-value="1" inactive-value="0" active-text="显示"
								inactive-text="隐藏"></el-switch>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="父级" prop="parent_id">
							<el-cascader v-model="temp.parent_id" :options="list" clearable :props="props"
								:show-all-levels="false" />
						</el-form-item>
						<el-form-item label="权限" prop="system_permission_id" style="width: 100%;">
							<el-cascader v-model="temp.permission_id" :options="permissionList" :props="props"
								placeholder="选择权限" @change="changeParent" clearable />
						</el-form-item>
						<el-form-item label="附加字段" prop="additional">
							<el-input v-model="temp.additional" />
						</el-form-item>
						<el-form-item label="显示排序" prop="order">
							<el-input v-model="temp.order" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-form-item label="菜单描述" prop="description">
					<el-input v-model="temp.description" :autosize="{ minRows: 3, maxRows: 5 }" type="textarea"
						placeholder="菜单描述" />
				</el-form-item>
			</el-form>
		</template>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="showEditForm = false">取消</el-button>
				<el-button type="primary" @click="submitForm" :disabled="submiting" :loading="submiting" :icon="Check">
					保存
				</el-button>
			</div>
		</template>
	</el-dialog>
</template>


<style scoped>
.icons-container {
	margin: 10px 20px 0;
	overflow: hidden;
}

.grid {
	position: relative;
	display: grid;
	grid-template-columns: repeat(auto-fill, minmax(40px, 1fr));
}

.icon-item {
	margin: 10px;
	text-align: center;
	float: left;
	color: #24292e;
	cursor: pointer;
}

.disabled {
	pointer-events: none;
}

.custom-tree-node {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: space-between;
	font-size: 14px;
	padding-right: 8px;
}
</style>
